package hjw.com.controller;


import hjw.com.dao.UserMapper;
import hjw.com.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.Map;


@Controller
@RequestMapping("/home")
@SuppressWarnings("all")
public class LoginController {

    @Autowired
    UserMapper userMapper;

    @GetMapping("/main")
    public String index(HttpServletRequest request,Model model){

        model.addAttribute("state","请登录!!!");

        //用于判断是否存在越界异常信息收集提示
        String state = (String) request.getAttribute("state");

        if (state != null) model.addAttribute("state",state);

        return "main/index";
    }

    @PostMapping("/login")
    public String doLogin(String phone, String pwd,
                          HttpServletRequest req,HttpServletResponse resp,
                          Model model){
        //是否已登录，再次登录会与其他登录用户冲突
        if (req.getSession().getAttribute("user") != null){
            model.addAttribute("state","登陆失败（已有用户在线）!!!");
            return "main/index";
        }

        //判断手机号是否为空值
        if (phone.equals("") || phone == null) {
            model.addAttribute("state","账户序列为空!!!");
            return "main/index";
        }
        //判断密码是否为空值
        if (pwd.equals("") || pwd == null) {
            model.addAttribute("state","密码序列为空!!!");
            return "main/index";
        }

        System.out.println("phone ="+phone + ",pwd =" + pwd);


        //获取相对应的账号密码对象
        User user = userMapper.findByPhone(phone);



        System.out.println("登录成功，账户：" + user);

        //账户数据库不存在
        if (user == null){
            System.out.println("登录失败-账号有误");
            model.addAttribute("state","数据异常，报错信息：手机号不存在!!!");
            return "main/index";
        }
        //账户数据库存在，密码错误
        if (!pwd.equals(user.getPwd())){
            System.out.println("数据异常，报错信息：密码错误");
            model.addAttribute("state","数据异常，报错信息：密码错误!!!");
            user = null;//清楚存储记录
            return "main/index";
        }

        //设置用户全局会话
        HttpSession session = req.getSession(true);
        session.setAttribute("user" ,user);
        return "main/index";
    }

    @RequestMapping("/source")
    @ResponseBody
    public String sevenDaysLogin(HttpServletRequest request, HttpServletResponse response, @RequestBody Map<String, String> map) {
        System.out.println("-ppppppppppppppppppppp-p-p-p-p-");

        String account = map.get("startDate");
        String pwd = map.get("endDate");
        String flag = map.get("planLanes");

        System.out.println(map.get("startDate"));
        System.out.println(map.get("endDate"));
        System.out.println(map.get("planLanes"));

        if (!("2022-01-25".equals(account) && "2022-01-28".equals(pwd))) {
            System.out.println("密码错误");
            return "error";
        }
        HttpSession session = request.getSession(true);
        if ("[1]".equals(flag)) {
            //使用7天免密登录功能   （这里注意一下，如果下一次登陆又点了七天免登陆，那么就会重新计算天数）

            Cookie cookie = new Cookie("JSEESIONID", session.getId());
            cookie.setMaxAge(60*60*24*7);

            session.setMaxInactiveInterval(60*60*24*7);
            session.setAttribute(session.getId(),"下次用户只需要带着没有失效的Cookie，在7天内就可以完成登录了。无需再次校验数据库中用户名密码信息。");

            String id = session.getId();
            System.out.println(cookie.getValue()+"......--------------服务端响应到客户端的cookie-id------------------...."+id);

            response.addCookie(cookie);
        } else {
            //不使用7天免密登录功能
            /*设置session的生命周期，，  180是三分钟*/
            request.getSession().setMaxInactiveInterval(180);
            /*设置cookie的jsessionid的值和生命周期*/
            Cookie c = new Cookie("JSESSIONID", request.getSession().getId());
            //关闭浏览器后，丢失Cookie
            c.setMaxAge(-1);
            /*将cookie放入到响应对象中*/
            response.addCookie(c);
        }

        //设置Session的名字。
        session.setAttribute("username","startDate");

        return "ok";
    }

    @GetMapping("/logout")
    public String logout(HttpSession session,Model model){
        session.invalidate();
        model.addAttribute("state","请重新登录");
        return "main/index";
    }

    @RequestMapping("/getLogin")
    @ResponseBody
    public String getLogin(HttpServletRequest request, HttpServletResponse response) {

        System.out.println("-pppppppppppppppppppppppppppppppppppppppppp-------------------------");

        Cookie[] cookies = request.getCookies();
        HttpSession session = request.getSession(true);

        Object[] objects = Arrays.stream(cookies).toArray();
        for (int i = 0; i < cookies.length; i++) {
            System.out.println(cookies[i].getName()+"...........客户端传上来的cookie........."+cookies[i].getValue());
            System.out.println(cookies[i].getMaxAge()+"....................");
        }



        Object attribute = session.getAttribute(cookies[0].getValue());

        System.out.println(attribute);

        return "OK";
    }


}
